import './index.scss';
import React, { Component } from 'react'
import services from 'services';
import classNames from 'classnames';
import PageLayout from 'layouts/Page';
import Steps from 'components/Steps';
import Input from 'components/Input';
import Button from 'components/Button';
import Timeline from 'components/Timeline';
import Radio from 'components/Radio';
import Container from 'components/Container';
import DatePicker from 'components/DatePicker';
import { loadingOn } from 'components/Loading';
import qs from 'qs';
import moment from 'moment';

@PageLayout({classNames: 'page-home', title: '填写信息' })
class Page extends Component {
  titles = {
    '0': '填写信息',
    '1': '勾选接种记录',
    '2': '上传资料',
    '3': '审核'
  }

  constructor(props) {
    super(props);

    this.state = {
      currentIndex: 0,
      state: 0,
      errors: {},
      name: '',
      birthday: '',
      sex: undefined,
      idcard: undefined,
      currentFileField: '',
      selectedVaccineIdList: [],
      paymentSlip: {
        file: '',
        src: ''
      },
      vaccineBook: {
        file: '',
        src: ''
      },
      isShowTips: false
    };

    this.stepsData = {
      steps: [
        { text: '填写信息' },
        { text: '勾选接种记录' },
        { text: '上传资料' },
        { text: '审核' },
      ]
    }

    //  parse parameters for API works
    let { message_id, crm_id, uid, nickname, activity_id } = qs.parse(location.href.split('?')[1]);

    this.messageId = message_id;
    this.crmId = crm_id;
    this.uid = uid;
    this.nickname = nickname;
    this.activity_id = activity_id;

    this.getVaccineList();
  }

  componentWillMount() {
    //  默认关闭页面
    this.props.setHeader({
      onBack: this.back
    });

    //  get last step
    services.Home.getVerifyStatus(this.messageId).then(res => {
      //  用户还没提交过, return
      if (res.data.success === 0) return;

      let { state, step, remark } = res.data.data;

      //  如果已提交则出现结果页
      if (state != 0) {
        this.setState({
          currentIndex: 3,
          state,
          remark
        });
        return;
      } 

      services.Home.getStepsRecord(this.messageId).then(res => {
        let { nickname, vcc_table: selectedVaccineIdList, info={} } = res.data.data;
        let { name, birthday, sex, idcard } = info;
        
        this.setState({
          currentIndex: step-1,
          state,
          nickname,
          remark,
          selectedVaccineIdList,
          name,
          birthday,
          sex,
          idcard
        });

        step-1 == 2 && this.showTips();
        this.updateTitle();
      });
    });
  }

  validInfo = () => {
    let { name, birthday, sex, idcard } = this.state;
    let errors = {};

    !name && (errors.name = '请输入接种人姓名');
    !birthday && (errors.birthday = '请选择接种人生日');
    sex === undefined && (errors.sex = '请选择接种人性别');
    idcard && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(idcard) && (errors.idcard = '身份证号码不正确');

    return Object.keys(errors).length ? this.setErrorsThenReturnFalse(errors) : true;
  }

  validSelectedVaccine = () => {
    let valid = this.state.selectedVaccineIdList.length > 0;
    valid === false &&  alert('请选择需要接种的疫苗');
    return valid;
  }

  updateTitle = () => {
    this.props.setHeader({
      title: this.titles[this.state.currentIndex]
    });
  }

  back = () => {
    let { currentIndex } = this.state;

    if ([0, 3].includes(currentIndex)) {
      location.href = 'jzapp://close_web_page';
    }
    else {
      this.setState({
        currentIndex: currentIndex - 1
      })
    }
  }

  next = () => {
    let { currentIndex, selectedVaccineIdList } = this.state;

    //  step 1
    if (currentIndex === 0 && this.validInfo()) {
      let { name, birthday, sex, idcard } = this.state;

      loadingOn();
      services.Home.sendStep1({
        id: this.messageId,
        uid: this.uid,
        nickname: this.nickname,
        name,
        birthday,
        sex,
        idcard,
        activity_id: this.activity_id
      }).then(res => {
        if (this.hasAPIError(res)) return;

        //  go step 2
        this.getVaccineList();
        this.goNext();
      });
    }
    //  step 2
    else if (currentIndex === 1 && this.validSelectedVaccine()) {
      loadingOn();
      services.Home.sendStep2({ id: this.messageId, vcc_table: selectedVaccineIdList }).then(res => {
        if (this.hasAPIError(res)) return;

        //  go step 3
        this.goNext();
        this.showTips();
      });
    }
    //  step 3
    else if (currentIndex === 2) {
      let paymentSlipFile = this.state.paymentSlip.file;
      let vaccineBookFile = this.state.vaccineBook.file;

      let bodyFormData = new FormData();
      bodyFormData.set('id', this.messageId);
      bodyFormData.append('payment_slip', paymentSlipFile);
      bodyFormData.append('vaccination_book', vaccineBookFile);

      loadingOn();
      services.Home.sendStep3(bodyFormData).then(res => {
        if (this.hasAPIError(res)) return;

        //  go step 4
        this.goNext();
      });
    }
  }

  showTips = () => {
    setTimeout(() => {
      this.setState({
        isShowTips: true
      });
    }, 500);
  }

  goNext = () => {
    let currentIndex = this.state.currentIndex;
    this.setState({ currentIndex: currentIndex+1 }, () => {
      this.updateTitle();
    });
  }

  hasAPIError(res) {
    if (res.data.success === 0) {
      alert(res.data.errmsg);
      return true;
    }

    return false;
  }

  getVaccineList = () => {
    services.Home.getVaccineList(this.messageId).then(res => {
      this.setState({
        timeline: res.data.data
      });
    });
  }

  setErrorsThenReturnFalse = (errors) => {
    this.setState({
      errors: { ...this.state.errors, ...errors }
    });

    return false;
  }

  renderError = (field) => {
    let error = this.state.errors[field];
    return error ? <div className="error">{error}</div> : null;
  }

  resetError = (field) => {
    let newErrors = { ...this.state.errors };
    delete newErrors[field];

    this.setState({
      errors: { ...newErrors }
    })
  }

  handleUpload = (input) => {
    //  format check
    let files = input.target.files || input.dataTransfer.files;

    if (!files.length) return;

    let isValid = [].every.call(files, file => /\.jpe?g|png$/.test(file.name.toLowerCase()));

    if (!isValid) return alert('请选择图片');

    let reader = new FileReader();

    reader.onload = (e) => {
      this.setState({
        [this.state.currentFileField]: {
          file: files[0],
          src: e.target.result
        }
      });
    };

    reader.readAsDataURL(files[0]);
  }

  toggleFilePicker = (fileField) => {
    this.setState({
      currentFileField: fileField
    });

    document.querySelector('.uploadInput').click();
  }

  onSelectVaccine = (selectedId) => {
    let selectedVaccineIdList = [...this.state.selectedVaccineIdList];
    let index = selectedVaccineIdList.findIndex(item => item === selectedId);

    if (index > -1) selectedVaccineIdList.splice(index, 1);
    else selectedVaccineIdList.push(selectedId);

    this.setState({ selectedVaccineIdList });
  }

  formatDate(date) {
    let d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
  }

  render() {
    let { 
      currentIndex, 
      name, 
      birthday, 
      sex, 
      idcard, 
      selectedVaccineIdList, 
      paymentSlip, 
      vaccineBook,
      state,
      remark,
      isShowTips,
    } = this.state;
    let content;
    let isSubmitDisabled;

    switch (currentIndex) {
      case 0:
        isSubmitDisabled = [name, birthday, sex].includes(undefined);
        content =  (
          <div className="card">
            <div className="row" onClick={this.resetError.bind(this, 'name')}>
              {this.renderError('name')}
              <div className="label">接种人姓名</div>
              <div className="label-for">
                <Input placeholder="请输入接种人姓名" value={name} onChange={val => this.setState({ name: val })} />
              </div>
            </div>

            <div className="row" onClick={this.resetError.bind(this, 'birthday')}>
              {this.renderError('birthday')}
              <div className="label">接种人生日</div>
              <div className="label-for">
                <DatePicker 
                  maxDate={new Date()}
                  date={birthday ? moment(birthday).toDate() : birthday} 
                  onChange={ date => this.setState({ birthday: moment(date).format('YYYY-MM-DD') })}
                >
                  <p>{birthday || '请选择接种人生日'}</p>
                </DatePicker>
              </div>
            </div>

            <div className="row" onClick={this.resetError.bind(this, 'sex')}>
              {this.renderError('sex')}
              <div className="label">接种人性别</div>
              <div className="label-for">
                <Radio checked={parseInt(sex) === 0} onClick={() => this.setState({ sex: 0 })} text="女"/>
                <Radio checked={parseInt(sex) === 1} onClick={() => this.setState({ sex: 1 })} text="男"/>
              </div>
            </div>
            
            <div className="row" onClick={this.resetError.bind(this, 'idcard')}>
              {this.renderError('idcard')}
              <div className="label">接种人身份证</div>
              <div className="label-for">
                <Input placeholder="可选填" value={idcard} onChange={val => this.setState({ idcard: val })} />
              </div>
            </div>
          </div>
        );
        break;

      case 1:
        isSubmitDisabled = selectedVaccineIdList.length === 0;  
        content = <Timeline data={this.state.timeline} onSelectVaccine={this.onSelectVaccine} selectedVaccineIdList={selectedVaccineIdList} />;
        break;

      case 2:
        isSubmitDisabled = [paymentSlip.src, vaccineBook.src].includes('');
        let uploadItems = [ 
          { field: 'paymentSlip', text: '上传五联缴费单' },
          { field: 'vaccineBook', text: '上传五联接种记录' }
        ].map((item, index) => {
          let imgSrc = this.state[item.field].src;

          return (
            <div 
              key={index} 
              className={classNames(`upload-item upload-item0${index+1}`, { selected: imgSrc })} 
              onClick={() => this.toggleFilePicker(item.field)}
            >
              <div className="preview">
                { imgSrc && <img src={imgSrc} alt=""/> }
                <div className="tips">点击重新上传</div>
              </div>
              <div className="text">{item.text}</div>
            </div>
          )
        });

        content = (
          <div className="upload">
            <div className="upload-bd">
              { uploadItems }
            </div>
            <div className="upload-ft">
              <div className="tips" onClick={() => this.setState({ isShowTips: true })}>拍照要点 <span className="tips-icon"></span></div>
            </div>

            <input 
              type="file" 
              accept="image/*" 
              onChange={e => this.handleUpload(e)}  
              onClick={e => (e.target.value = null)}
              className="uploadInput" 
            />

            <div className={classNames('picture-tips', { active: isShowTips })}>
              <div className="bd">
                <div className="picture-tips-button" onClick={() => this.setState({ isShowTips: false })}></div>
              </div>
            </div>
          </div>
        );
        break;

      case 3:
          let result = ({ 
            '0': { title: '等待审核', para: '您的疫苗补贴申请已成功提交，请耐心等待审核' }, 
            '1': { title: '审核通过', para: '客服将在1-2个工作日内，通过聊天窗把补贴券包<br/>推送给您，通过微信扫码或识别可领取补贴' }, 
            '2': { title: '审核未通过', para: `失败原因：${remark}` } 
          })[state];

          content = (
            <div className="result">
              <h2>{result.title}</h2>
              <p dangerouslySetInnerHTML={{__html: result.para }}></p>
            </div>
          );
          break;
    }

    return (
      <div className={`steps${currentIndex+1}`}>
        <Steps {...this.stepsData} currentIndex={currentIndex} />

        <Container>
          { content }
          
          <Button
            type={`block primary`} 
            disabled={isSubmitDisabled} 
            onClick={() => { !isSubmitDisabled && this.next() }}
          >
            {currentIndex < 2 ? '下一步' : '提交'}
          </Button>
        </Container>
      </div>
    )
  }
}

export default Page;